package org.txazo.blog.commons.io;

import org.txazo.blog.commons.io.base.Reader;
import org.txazo.blog.commons.io.base.Writer;

public class StringLineReader implements Reader {

	private StringBuilder sb = null;

	/** 当前行起始字符位置 */
	private int startChar = 0;
	/** 下一行起始字符位置 */
	private int nextChar = 0;
	/** 是否读完 */
	private boolean readOff = false;
	/** 分隔符 */
	private static String lineSeparator = System.getProperty("line.separator");
	/** 分隔符长度 */
	private static int lineSeparatorLength = lineSeparator.length();

	public StringLineReader(Writer writer) {
		this.sb = writer.getOut();
	}

	@Override
	public String readLine() {
		if (readOff) {
			return null;
		}

		startChar = nextChar;
		int index = sb.indexOf(lineSeparator, startChar);

		if (index == -1) {
			index = sb.length();
			readOff = true;
		}

		nextChar = index + lineSeparatorLength;

		return sb.substring(startChar, index);
	}

	@Override
	public void close() {
		sb = null;
	}

}
